import {
  adoptRecord,
  initSaveActiveTreeAssignOrganization,
  selectCuesActive,
} from '@/services/api/api-cues-active';
import { cuesAttachmentPreview } from '@/services/api/api-cues-attachment';
import { DownloadOutlined } from '@ant-design/icons';
import { ModalForm, ProFormCascader } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import {
  Alert,
  Button,
  Cascader,
  Descriptions,
  Divider,
  Image,
  message,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import ReceiptActive from './ReceiptActive';

interface DetailsActiveProps {
  id: string;
  name: string;
  onRefurbish: () => void;
  submitId: string;
}

const DetailsActive: React.FC<DetailsActiveProps> = ({ id, name, onRefurbish, submitId }) => {
  const access = useAccess();

  const [details, setDetailsState] = useState<CuesActiveData.ActiveDetails>();

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);
  const [drawerFormVisible, setDrawerFormVisible] = useState(false);
  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  useEffect(() => {
    if (submitId === id) {
      if (submitId !== undefined) {
        setDrawerFormVisible(true);
      }
    }
  }, []);

  const iframeRef = useRef(null);

  const handleLoad = () => {
    console.log('加载完成');
    setPreviewLoading(false);
  };
  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);

  /**
   * 获取 详情
   * @param key
   */
  const loadSubmitDetails = async () => {
    try {
      const response = await selectCuesActive({ id });
      if (response.code === 0) {
        setDetailsState(response.data);
        console.log('=======', details?.cascaderAssignOrganizations);
      }
    } catch (error) {}
  };

  /**
   * 推送单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadInitSaveActiveTreeAssignOrganization = async () => {
    try {
      const response = await initSaveActiveTreeAssignOrganization({
        id,
      });
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={details?.articleName}
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
        width: 900,
      }}
      trigger={<a>{name}</a>}
      onOpenChange={(visible) => {
        if (visible) {
          loadInitSaveActiveTreeAssignOrganization();
          loadSubmitDetails();
        } else {
          setTreeAssignOrganizationDataState([]);
        }
        setDrawerFormVisible(visible);
      }}
      open={drawerFormVisible}
      submitter={{
        render: (props, dom) => {
          return [
            access.选题计划x收录 && details?.isAdopt === 0 && (
              <ModalForm
                title="是否收录"
                trigger={<Button type="primary">收录</Button>}
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  destroyOnClose: true,
                }}
                onFinish={async (values) => {
                  const response = await adoptRecord({ id, channel: 2 });
                  if (response.code === 0) {
                    message.success('收录成功！');
                    loadSubmitDetails();
                    return true;
                  }
                }}
              >
                {name}
              </ModalForm>
            ),
          ];
        },
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        {details !== undefined && (
          <>
            <Descriptions>
              <Descriptions.Item label="报送单位">
                {details?.articleOrganizationName}
              </Descriptions.Item>
              <Descriptions.Item label="报送人">{details?.articleAccountName}</Descriptions.Item>
              {/* <Descriptions.Item label="联系方式">{details?.articleAccountPhone}</Descriptions.Item> */}
              <Descriptions.Item label="报送时间">{details?.createdTime}</Descriptions.Item>
              {access.线索征集x配置x管理员 && (
                <Descriptions.Item label="查阅媒体">
                  <ReceiptActive id={details.id} receipt={details.receipt} />
                </Descriptions.Item>
              )}
            </Descriptions>
            {access.线索征集x配置x管理员 &&
              Array.isArray(details?.adoptOrganizationNames) &&
              details?.adoptOrganizationNames.length > 0 && (
                <Descriptions>
                  <Descriptions.Item label="收录单位">
                    <Space size={[0, 8]} wrap>
                      {Array.isArray(details?.adoptOrganizationNames) &&
                        details?.adoptOrganizationNames?.map((item) => {
                          return <Tag key={item}>{item}</Tag>;
                        })}
                    </Space>
                  </Descriptions.Item>
                </Descriptions>
              )}
            <Descriptions>
              <Descriptions.Item label="选题方向">
                <Space size={[0, 8]} wrap>
                  {details?.articleIndustrys?.map((item) => {
                    return <Tag key={item.value}>{item.label}</Tag>;
                  })}
                </Space>
              </Descriptions.Item>
            </Descriptions>
            <Descriptions>
              <Descriptions.Item label="标签">
                {details?.articleLabels.map((item) => {
                  return <Tag key={item.value}>{item.label}</Tag>;
                })}
              </Descriptions.Item>
            </Descriptions>
            {details?.articleSetDate && (
              <Descriptions column={3}>
                <Descriptions.Item label="线索日期">{details?.articleSetDate}</Descriptions.Item>
              </Descriptions>
            )}
            {details?.articleLocation && (
              <Descriptions column={3}>
                <Descriptions.Item label="地点">{details?.articleLocation}</Descriptions.Item>
              </Descriptions>
            )}
            {details?.articleHighlight && (
              <Descriptions column={3}>
                <Descriptions.Item label="亮点">{details?.articleHighlight}</Descriptions.Item>
              </Descriptions>
            )}
            {details?.contacts && (
              <Descriptions>
                <Descriptions.Item span={3} label="联络方式">
                  <Space size={[8, 16]} wrap>
                    {details?.contacts &&
                      details?.contacts.map((item) => (
                        <span style={{ marginRight: 5 }}>
                          <a>{item.name}</a> - <a>{item.phone}</a>
                        </span>
                      ))}
                  </Space>
                </Descriptions.Item>
              </Descriptions>
            )}
            <div
              style={{
                marginTop: 24,
              }}
            >
              <ProFormCascader
                width="xl"
                label="邀请采访单位："
                name="assignOrganizationIds"
                placeholder="选择单位"
                fieldProps={{
                  value: details?.cascaderAssignOrganizations,
                  options: treeAssignOrganizationData,
                  multiple: true,
                  removeIcon: false,
                  allowClear: false,
                  maxTagCount: 'responsive',
                  showCheckedStrategy: Cascader.SHOW_CHILD,
                }}
              />
            </div>
            <Divider />
            {details?.articleName ? (
              <Typography.Title level={3} style={{ textAlign: 'center' }}>
                {details?.articleName}
              </Typography.Title>
            ) : (
              <Typography.Title level={3} style={{ textAlign: 'center' }}>
                暂无标题
              </Typography.Title>
            )}
            <br />
            {details?.articleContent ? (
              <div
                dangerouslySetInnerHTML={{
                  __html: `${details?.articleContent}`,
                }}
              />
            ) : (
              <>暂无内容</>
            )}

            {details?.articleAttachments && details?.articleAttachments.length > 0 && (
              <>
                <Divider />
                <div
                  style={{
                    textAlign: 'right',
                  }}
                >
                  <Button
                    type="primary"
                    key="import"
                    size="small"
                    icon={<DownloadOutlined />}
                    onClick={() => {
                      details?.articleAttachments.forEach(function (item) {
                        window.open(item.content, '_blank');
                      });
                    }}
                  >
                    全部下载
                  </Button>
                </div>

                <Upload
                  listType="picture"
                  multiple
                  fileList={details?.articleAttachments.map((item) => {
                    return {
                      uid: item.id,
                      name: item.name,
                      url: item.content,
                      mimeType: item.mimeType,
                      status: 'done',
                    };
                  })}
                  showUploadList={{
                    downloadIcon: (
                      <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                        <DownloadOutlined
                          style={{
                            marginRight: '10px',
                          }}
                        />
                        点击下载
                      </div>
                    ),
                    showRemoveIcon: false,
                    showDownloadIcon: true,
                  }}
                  onPreview={async (file: UploadFile) => {
                    setPreviewData({
                      id: file.uid,
                      name: file.name,
                      mimeType: file.mimeType,
                      url: encodeURI(file.url),
                    });
                    setPreviewOpen(true);
                  }}
                />
                <DrawerForm
                  title={previewData?.name}
                  drawerProps={{
                    width: 900,
                    destroyOnClose: true,
                  }}
                  open={previewOpen}
                  onOpenChange={async (visible) => {
                    if (visible) {
                      if (
                        previewData?.mimeType !== null &&
                        previewData?.mimeType?.indexOf('image') > -1
                      ) {
                        //图片预览
                      } else {
                        setPreviewLoading(true);

                        const response = await cuesAttachmentPreview({
                          id: previewData?.id,
                        });

                        if (response.code === 0) {
                          setPreviewOnlineUrl(response.data);
                        } else {
                          message.error('暂时无法预览');
                          setPreviewLoading(false);
                        }
                      }
                    } else {
                      setPreviewOpen(false);
                      setPreviewData(undefined);
                      setPreviewOnlineUrl(undefined);
                    }
                  }}
                  submitter={{
                    searchConfig: {
                      submitText: '下载',
                    },
                  }}
                  onFinish={async (values) => {
                    window.open(previewData?.url, '_blank');
                  }}
                >
                  <Alert
                    style={{
                      marginBottom: 20,
                    }}
                    message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                    type="warning"
                    showIcon
                  />
                  {previewData?.mimeType !== null &&
                  previewData?.mimeType?.indexOf('image') > -1 ? (
                    <Image width="100%" src={previewData?.url} />
                  ) : (
                    <Spin spinning={previewLoading}>
                      <iframe
                        ref={iframeRef}
                        src={previewOnlineUrl}
                        height={windowSize.innerHeight - 220}
                        width="100%"
                        frameBorder="0"
                        // scrolling="false"
                        allowFullScreen={true}
                        // scrolling={'no'}
                      />
                    </Spin>
                  )}
                </DrawerForm>
              </>
            )}
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailsActive;
